package com.fzc.rhinooffice.module.workbench;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.fzc.rhinooffice.R;
import com.fzc.rhinooffice.common.RemoteInvoke;
import com.fzc.rhinooffice.common.SysApplication;
import com.fzc.rhinooffice.common.utils.CommonUtil;
import com.fzc.rhinooffice.common.utils.FileUtil;
import com.fzc.rhinooffice.common.utils.ImageTools;
import com.fzc.rhinooffice.common.utils.StringUtil;
import com.fzc.rhinooffice.common.view.HorizontalListView;
import com.fzc.rhinooffice.config.AppConfig;
import com.fzc.rhinooffice.module.BaseActivity;
import com.fzc.rhinooffice.module.CommonAdapter;
import com.fzc.rhinooffice.module.ViewHolder;
import com.fzc.rhinooffice.module.entity.AttachmentRecord;
import com.fzc.rhinooffice.module.entity.SortModel;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

@SuppressLint("NewApi")
public class AddEmailActivity extends BaseActivity implements OnClickListener, OnItemClickListener {
	
	private final int TAKE_PIC = 0;
	private final int TAKE_PHOTO = 1;
	private final int TAKE_FILE = 3;
	private final int SCALE = 2;//照片缩小比例
	private final int ADD_RECEIVER = 4;
	
	@ViewInject(R.id.ll_parent)
	private LinearLayout ll_parent;
	
	@ViewInject(R.id.iv_back)
	private ImageView iv_back;
	
	@ViewInject(R.id.tv_title)
	private TextView tv_title;
	
	@ViewInject(R.id.tv_filter)
	private TextView tv_filter;
	
	@ViewInject(R.id.edt_to_id)
	private EditText edt_to_id;					//输入收件人
	
	@ViewInject(R.id.imb_add_id)
	private ImageButton imb_add_id;				//查找邮箱联系人
	
	@ViewInject(R.id.edt_theme)
	private EditText edt_theme;					//主题
	
	@ViewInject(R.id.imb_add_attachment)
	private ImageButton imb_add_attachment;		//添加附件
	
	@ViewInject(R.id.edt_content)
	private EditText edt_content;					//邮件内容
	
	private PopupWindow myPopupWindow;
	
	private View popupView;
	
	private ImageView iv_take_pic;	//选择图片
	
	private ImageView iv_take_photo;	//拍照
	
	private ImageView iv_take_file;	//选择文件
	
	private HorizontalListView hlv_attach;	
	
	private List<AttachmentRecord> attachList;
	
	private List<SortModel> smList;		//收件人列表
	
	private CommonAdapter<AttachmentRecord> commonAdapter;
	
	private AlertDialog.Builder builder;
	
	private Intent mIntent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initUI();
	}
	
	private void initUI(){
		setContentView(R.layout.activity_add_email);
		ViewUtils.inject(this);
		tv_title.setText("写邮件");
		tv_filter.setText("发送");
		tv_filter.setBackground(null);
		mIntent = getIntent();
		if(mIntent!=null){
			if(!StringUtil.isEmpty(mIntent.getStringExtra("from_id"))){
				edt_to_id.setText(mIntent.getStringExtra("from_id"));
			}
		}
		
		popupView = getLayoutInflater().inflate(R.layout.pop_add_attach_view, null);
		popupView.setFocusable(true);
		myPopupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		myPopupWindow.setTouchable(true);
		myPopupWindow.setOutsideTouchable(true);
		myPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.write));
		myPopupWindow.setFocusable(true);
		myPopupWindow.setAnimationStyle(R.style.MyPopAnim);
		
		iv_take_pic = (ImageView) popupView.findViewById(R.id.iv_take_pic);
		iv_take_photo = (ImageView) popupView.findViewById(R.id.iv_take_photo);
		iv_take_file = (ImageView) popupView.findViewById(R.id.iv_take_file);
		hlv_attach = (HorizontalListView) popupView.findViewById(R.id.hlv_attach);
		iv_take_pic.setOnClickListener(this);
		iv_take_photo.setOnClickListener(this);
		iv_take_file.setOnClickListener(this);
		hlv_attach.setOnItemClickListener(this);
		initAdapter();
		smList = new ArrayList<SortModel>();
	}
	
	private Handler mHandler = new Handler(){
		
		@Override
		public void handleMessage(android.os.Message msg) {
			
			switch (msg.what) {
			case 8:
				//邮件发送成功
				StringUtil.showToast((String)msg.obj);
				finish();
				break;
			case -8:
				//邮件发送失败
				StringUtil.showToast((String)msg.obj);
				break;
			}
		};
	};
	
	private void initAdapter(){
		if(attachList==null){
			attachList = new ArrayList<AttachmentRecord>();
		}
		
		if(commonAdapter==null){
			commonAdapter = new CommonAdapter<AttachmentRecord>(this,attachList,R.layout.pop_attach_item_view) {

				@Override
				public void convert(ViewHolder holder, AttachmentRecord item) {
					if(item.bm==null){
						holder.setImageResource(R.id.iv_file_image, R.drawable.txt_icon);
					}else{
						holder.setImageBitmap(R.id.iv_file_image, item.bm);
					}
					holder.setText(R.id.tv_file_size, item.name);
					//holder.setText(R.id.tv_file_size, item.fileSize+"B");
				}
				
			};
			hlv_attach.setAdapter(commonAdapter);
		}else{
			commonAdapter.notifyDataSetChanged();
		}
	}
	
	@OnClick(R.id.iv_back)
	private void goBack(View v){
		super.back();
	}
	
	//选择收件人
	@OnClick(R.id.imb_add_id)
	private void choseReceiver(View v){
		mIntent = new Intent(this,ContactsActivity.class);
		startActivityForResult(mIntent, ADD_RECEIVER);
	}
	
	//添加附件
	@OnClick(R.id.imb_add_attachment)
	private void addAttachment(View v){
		if(myPopupWindow!=null && myPopupWindow.isShowing()){
			myPopupWindow.dismiss();
		}else{
			myPopupWindow.showAtLocation(ll_parent, Gravity.BOTTOM, 0, 0);
		}
		
	}
	
	@OnClick(R.id.tv_filter)
	private void send(View v){
		
		if(StringUtil.isEmpty(edt_to_id.getText()+"")){
			StringUtil.showToast("请填写收件人地址后再发送！");
			edt_to_id.requestFocus();
			return;
		}
		
		String theme;	//邮件标题
		if(StringUtil.isEmpty(edt_theme.getText()+"")){
			theme = "来自"+SysApplication.user.a_user_name+"的邮件";
			edt_theme.setText(theme);
		}else{
			theme = edt_theme.getText()+"";
		}
		
		String content = edt_content.getText()+"";
		//发送
		RemoteInvoke.email_add(mHandler, StringUtil.getCurrentTimeStr(null), edt_to_id.getText()+"",theme, content, "/storage/emulated/0/youku/pushservice/pushsdk.db");
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode==RESULT_OK){
			if(requestCode==TAKE_PHOTO){
				
				//将保存在本地的图片取出并缩小后显示在界面上
				Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+AppConfig.PIC_PATH+"/temp.jpg");
				Bitmap newBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
				//由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
				bitmap.recycle();
				
				//将处理过的图片显示在界面上，并保存到本地
				String bmName = String.valueOf(System.currentTimeMillis());
				String bmPath = Environment.getExternalStorageDirectory().getAbsolutePath()+AppConfig.PIC_PATH;
				ImageTools.savePhotoToSDCard(newBitmap,bmPath, bmName);
	                      
                AttachmentRecord temp  = new AttachmentRecord();
                temp.bm = newBitmap;
                temp.name = bmName;
                temp.sdPath = bmPath;
                temp.fileSize = newBitmap.getByteCount()+"";
                if(!isExist(temp)){
                	attachList.add(temp);
                    initAdapter();
                }
	            
			}else if(requestCode==TAKE_PIC){
				ContentResolver resolver = getContentResolver();
				//照片的原始资源地址
				Uri originalUri = data.getData();
				String path = FileUtil.getPath(this, originalUri);
	            try {
	            	//使用ContentProvider通过URI获取原始图片
					Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
					if (photo != null) {
						//为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
						Bitmap smallBitmap = ImageTools.zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE);
						//释放原始图片占用的内存，防止out of memory异常发生
						photo.recycle();
						
						AttachmentRecord temp  = new AttachmentRecord();
	                    temp.bm = smallBitmap;
	                    temp.name = path.substring(path.lastIndexOf("/") + 1);
	                    temp.fileSize = smallBitmap.getByteCount()+"";
	                    if(!isExist(temp)){
	                    	attachList.add(temp);
		                    initAdapter();
	                    }
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}  
			}else if(requestCode==TAKE_FILE){
				Uri uri = data.getData();
				
	            String path = FileUtil.getPath(this, uri);
	            AttachmentRecord temp  = new AttachmentRecord();
	            if(!StringUtil.isEmpty(path)){
	            	File file = new File(path);
	            	temp.sdPath = path;
	            	//temp.name = path.substring(path.lastIndexOf("/") + 1); 
	            	temp.name = file.getName();
	            	temp.fileSize = file.length()+"";
	            }
	            if(!isExist(temp)){
                	attachList.add(temp);
                    initAdapter();
                }
			}else if(requestCode==ADD_RECEIVER){
				//返回收件人列表
				List<SortModel> list = (List<SortModel>) data.getSerializableExtra("result");
				smList.addAll(list);
				for(int i=0;i<smList.size();i++){
					edt_to_id.setText(edt_to_id.getText()+smList.get(i).getName()+",");
				}
			}
		}
		
		
	}
	
	

	@Override
	public void onClick(View v) {
		
		if(v.getId() == R.id.iv_take_pic){
			
			mIntent = new Intent(Intent.ACTION_GET_CONTENT);
			mIntent.setType("image/*");
			startActivityForResult(mIntent, TAKE_PIC);
		}else if(v.getId() == R.id.iv_take_photo){
			
			mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+AppConfig.PIC_PATH,"temp.jpg"));
			mIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			startActivityForResult(mIntent, TAKE_PHOTO);
		}else if(v.getId() == R.id.iv_take_file){
			mIntent = new Intent(Intent.ACTION_GET_CONTENT); 
			mIntent.setType("*/*"); 
			mIntent.addCategory(Intent.CATEGORY_OPENABLE);
			try {
		        startActivityForResult( Intent.createChooser(mIntent, "Select a File to Upload"), TAKE_FILE);
		    } catch (android.content.ActivityNotFoundException ex) {
		    	StringUtil.showToast("Please install a File Manager!");
		    }
		}
	}
	
	/**
	 * 
	 * @param attach
	 * @return true 标识当前要添加的附件已经列表中已经存在
	 */
	private boolean isExist(AttachmentRecord attach){
		if(attach==null){
			return false;
		}
		for(int i=0;i<attachList.size();i++){
			if(attach.name.equals(attachList.get(i).name)){
				return true;
			}
		}
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		showActionDialog(position);
	}
	
	private void showActionDialog(final int position){
		//	    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //    设置Title的图标
        builder.setIcon(R.drawable.ic_launcher);
        //    设置Title的内容
        builder.setTitle("犀牛提醒您");
        //    设置Content来显示一个信息
        builder.setMessage("确定删除吗？");
        //    设置一个PositiveButton
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which){
            	
            	dialog.dismiss();
            	attachList.remove(position);
            	initAdapter();
            }
        });
        //    设置一个NegativeButton
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which){
            
            	dialog.dismiss();
            }
        });
        builder.show();
	}
	
}
